package cn.b.sky.mes.em.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.b.sky.mes.em.enums.EquipmentRepairCode;
import cn.b.sky.mes.em.model.RepairOrderPart;
import cn.b.sky.mes.em.model.condition.RepairOrderCondition;
import cn.b.sky.mes.em.service.RepairOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.em.model.RepairOrder;
import cn.b.sky.mes.em.model.RepairOrderCause;
import cn.b.sky.shop.activiti.constans.GlobalDefine;
import cn.b.sky.shop.activiti.enums.ProcessInstanceStatusEnum;
import cn.b.sky.shop.activiti.service.WorkFlowFacade;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.NumberRuleService;
import cn.b.sky.user.service.model.ECode;

/**
 * <strong>Title : EquipmentRepairController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.em.controller<br></strong>
 * <strong>Description : </strong>设备维修控制器<br> 
 * <strong>Create on : 2015年11月9日 下午1:19:31<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/equipmentRepair/*")
public class RepairOrderController extends SecurityController {

  @Resource
  ECodeService eCodeService;

  @Resource
  RepairOrderService repairService;

  @Resource
  WorkFlowFacade workFlowFacade;

  @Resource
  NumberRuleService numberRuleService;

  @RequestMapping("repair_list")
  public String selectEquipmentRepairListByCondition(String navTabId, Model model,
      @ModelAttribute("condition") RepairOrderCondition condition) {
    condition.setSiteCode(getSiteCode());
    List<RepairOrder> list = repairService.selectRepairOrderListByCondition(condition);
    int count = repairService.selectRepariOrderCountByCondition(condition);

    List<ECode> processECode = eCodeService.selectECodeList(ECodeEnums.PROCESSINSTANCE_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    for (RepairOrder order : list) {
      String processStatus = workFlowFacade.getProcessInstanceStatus(order.getBusinessKey(), getSiteCode());
      order.setProcessStatus(processStatus);
    }
    condition.setData(list);
    condition.setTotalCount(count);

    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());

    model.addAttribute("ECode", eCode);
    model.addAttribute("processECode", processECode);
    model.addAttribute("page", condition);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("step", EquipmentRepairCode.VALIDATED.getValue());

    return "em/equipmentRepair/repairOrder_list";
  }

  @RequestMapping("viewRepairOrder")
  public String viewRepairOrder(String navTabId, Model model, String id) {
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    RepairOrder repairOrder = repairService.getRepairOrder(id, getSiteCode());
    if (repairOrder.getStatusECode().equals(EquipmentRepairCode.PROCESSED.getValue())
        || repairOrder.getStatusECode().equals(EquipmentRepairCode.VALIDATED.getValue())) {
      List<RepairOrderCause> causes = repairService.getRepairOrderCause(id, getSiteCode());
      List<RepairOrderPart> parts = repairService.getRepairOrderPart(id, getSiteCode());
      repairOrder.setCauses(causes);
      repairOrder.setParts(parts);
    }
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("step", EquipmentRepairCode.VALIDATED.getValue());
    model.addAttribute("ECode", eCode);
    return "em/equipmentRepair/repairOrder_view";
  }

  @RequestMapping("requestRepair_list")
  public String selectRequestRepairList(String navTabId, Model model,
      @ModelAttribute("condition") RepairOrderCondition condition) {
    if (StringUtils.isBlank(condition.getStatusECode())) {
      condition.setStatusECode(EquipmentRepairCode.PENDING.getValue());
    }

    condition.setStatusECode(condition.getStatusECode());
    condition.setSiteCode(getSiteCode());
    List<RepairOrder> list = repairService.selectRepairOrderListByCondition(condition);
    int count = repairService.selectRepariOrderCountByCondition(condition);
    List<ECode> processECode = eCodeService.selectECodeList(ECodeEnums.PROCESSINSTANCE_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    for (RepairOrder order : list) {
      String processStatus = workFlowFacade.getProcessInstanceStatus(order.getBusinessKey(), getSiteCode());
      order.setProcessStatus(processStatus);
    }
    condition.setData(list);
    condition.setTotalCount(count);

    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());

    model.addAttribute("ECode", eCode);
    model.addAttribute("processECode", processECode);
    model.addAttribute("step", 0);
    model.addAttribute("page", condition);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/repairOrder_list";
  }

  @RequestMapping("addRequestRepair")
  public String addRequestRepair(String navTabId, Model model, String id) {
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    String alt = getImeViewMessageI18n(null,
        "SystemGenerateAutomatically.C");
    RepairOrder repairOrder = new RepairOrder();
    repairOrder.setRequestUser(SecurityContextUtil.getCurrentUserName());
    repairOrder.setOrderCode(alt);
    repairOrder.setStatusECode(EquipmentRepairCode.PENDING.getValue());
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute("ECode", eCode);
    model.addAttribute("pattern", "add");
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_add";
  }

  @RequestMapping("showBusinessImg")
  public String viewRepairOrderProcess(String navTabId, Model model, String id) {
    RepairOrder repairOrder = repairService.getRepairOrder(id, getSiteCode());
    String businessKey = repairOrder.getBusinessKey();

    String redirect = SystemConstant.IME_BASEURL + "/workflow/showBusinessImg?";
    redirect += GlobalDefine.WorkFlow.BUSINESSKEY + "=" + businessKey;

    return "redirect:" + redirect;
  }

  @RequestMapping("preShowBussinessImg")
  @ResponseBody
  public DWZResult preShowBussinessImg(String orderCode) {
    if (StringUtils.isBlank(orderCode)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }

    RepairOrder repairOrder = repairService.getRepairOrder(orderCode, getSiteCode());
    String processStatus = workFlowFacade.getProcessInstanceStatus(repairOrder.getBusinessKey(), getSiteCode());
    if (!StringUtils.isBlank(processStatus) && !ProcessInstanceStatusEnum.NOTSTART.getValue().equals(processStatus)) {
      return ajaxDone(null);
    } else {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "repairOrderHasNotStartedProcess.M"));
    }
  }

  @RequestMapping("preModifyRepairOrder")
  @ResponseBody
  public DWZResult preModifyRepairOrder(String orderCode) {
    if (StringUtils.isBlank(orderCode)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }

    RepairOrder repairOrder = repairService.getRepairOrder(orderCode, getSiteCode());
    String processStatus = workFlowFacade.getProcessInstanceStatus(repairOrder.getBusinessKey(), getSiteCode());
    if (!StringUtils.isBlank(processStatus) && !ProcessInstanceStatusEnum.NOTSTART.getValue().equals(processStatus)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "repairOrderStartProcessCanNotModify.M"));
    } else {
      return ajaxDone(null);
    }
  }

  @RequestMapping("modifyRequestRepair")
  public String modifyRequestRepair(String navTabId, Model model, String id, String bussinessKey) {
    RepairOrder repairOrder = null;
    if (StringUtils.isBlank(id) && !StringUtils.isBlank(bussinessKey)) {
      repairOrder = repairService.getOrderByBusinessKey(bussinessKey, SecurityContextUtil.getSiteCode());
    } else {
      repairOrder = repairService.getRepairOrder(id, getSiteCode());
      repairOrder.setRequestUser(SecurityContextUtil.getCurrentUserName());
    }
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("pattern", "modify");
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_add";
  }

  @RequestMapping("reModifyRequestRepair")
  public String reModifyRequestRepair(String navTabId, Model model, String bussinessKey) {
    RepairOrder repairOrder = repairService.getOrderByBusinessKey(bussinessKey, SecurityContextUtil.getSiteCode());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("pattern", "add");
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_reApply";
  }

  @RequestMapping("viewRequestRepair")
  public String viewRequestRepair(String navTabId, Model model, String id) {
    RepairOrder repairOrder = repairService.getRepairOrder(id, getSiteCode());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("pattern", "read");
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_view";
  }

  @RequestMapping("submitRepairOrder")
  public String submitRepairOrder(String navTabId, Model model, String id) {
    RepairOrder repairOrder = repairService.getRepairOrder(id, getSiteCode());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());

    List<ECode> processECode = eCodeService.selectECodeList(ECodeEnums.PROCESSINSTANCE_STATUS.getCode(),
        SecurityContextUtil.getLanguageCode());

    String processStatus = workFlowFacade.getProcessInstanceStatus(repairOrder.getBusinessKey(), getSiteCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("processECode", processECode);
    model.addAttribute("processStatus", processStatus);
    model.addAttribute("pattern", "modify");
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_submit";
  }

  /**
   * 启动维修流程
   *
   *
   */

  @RequestMapping("startTask")
  @ResponseBody
  public DWZResult startTask1(String navTabId, String operation, HttpServletRequest request,
      HttpServletResponse response, RepairOrder order) {
    if ("insert".equals(operation)) {
      setCreateInfo(order);
      order.setSiteCode(getSiteCode());
      order.setStatusECode(EquipmentRepairCode.PENDING.getValue());
      String orderCode = numberRuleService.selectNextNumber(getSiteCode(), "REPAIRORDERCODE");
      order.setOrderCode(orderCode);
      order.setRequestDateTime(new Date());
      repairService.insertRepairOrder(order);
    } else {
      order = repairService.getRepairOrder(order.getOrderCode(), getSiteCode());
      //更新报工时间
      order.setRequestDateTime(new Date());
      repairService.modifyRepairOrder(order);
    }

    String businessKey = order.getBusinessKey();
    String flowMapKey = request.getParameter(GlobalDefine.WorkFlow.PROCESSDEFINITIONKEY);
    String forwardUrl = this.getForwardUrl(request) + "/workflow/startTask?";
    forwardUrl += GlobalDefine.WorkFlow.BUSINESSKEY + "=" + businessKey;
    forwardUrl += "&flowMap_" + GlobalDefine.WorkFlow.PROCESSDEFINITIONKEY + "=" + flowMapKey;

    return dialogAjaxDone("saveSuccessfullyProcessStarted.M", navTabId, null, forwardUrl, null);
  }

  @RequestMapping(value = "saveRequestRepair")
  @ResponseBody
  public DWZResult saveRequestRepair(Model model, String pattern, String navTabId, String id, RepairOrder order,
      HttpServletRequest request) {
    if (order == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    setCreateInfo(order);
    order.setSiteCode(getSiteCode());
    order.setStatusECode(EquipmentRepairCode.PENDING.getValue());
    order.setRequestDateTime(new Date());
    if ("add".equals(pattern)) {
      String orderCode = numberRuleService.selectNextNumber(this.getSiteCode(), "REPAIRORDERCODE");
      order.setOrderCode(orderCode);
      repairService.insertRepairOrder(order);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          navTabId, null, null, null);
    } else {
      order.setOrderCode(id);
      repairService.modifyRepairOrder(order);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          navTabId, null, null, null);
    }
  }

  @RequestMapping("deleteRequestRepair")
  @ResponseBody
  public DWZResult deleteRequestRepair(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String[] orders = ids.split(",");
    int len = orders.length;
    BatchJobReport[] reports = new BatchJobReport[len];
    int failureCount = 0;
    for (int i = 0; i < orders.length; i++) {
      reports[i] = repairService.deleteRepairOrders(orders[i], getSiteCode());
      if (!reports[i].isSuccess()) {
        failureCount += 1;
      }
    }
    if (failureCount == 0) {
      //直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }
  }

  @RequestMapping("auditReceiveOrder")
  public String auditReceiveOrder(String navTabId, Model model,
      @ModelAttribute("condition") RepairOrderCondition condition, String bussinessKey) {
    RepairOrder repairOrder = repairService.getOrderByBusinessKey(bussinessKey, SecurityContextUtil.getSiteCode());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("pattern", "audit");
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/requestRepair_form";
  }

  @RequestMapping("receiveOrder")
  @ResponseBody
  public DWZResult receiveOrder(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String[] orders = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(orders.length);
    int failureCount = 0;
    for (int i = 0; i < orders.length; i++) {
      BatchJobReport report = repairService.doReceiveRepairOrder(orders[i], getSiteCode());
      reports.add(report);
      if (!report.isSuccess()) {
        failureCount += 1;
      }
    }
    if (failureCount == 0) {
      //直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  @RequestMapping("recordOrder")
  public String recordOrder(String navTabId, Model model, String bussinessKey) {
    RepairOrder repairOrder = repairService.getOrderByBusinessKey(bussinessKey, getSiteCode());
    String id = repairOrder.getOrderCode();
    List<RepairOrderCause> causes = repairService.getRepairOrderCause(id, getSiteCode());
    List<RepairOrderPart> parts = repairService.getRepairOrderPart(id, getSiteCode());
    repairOrder.setCauses(causes);
    repairOrder.setParts(parts);
    repairOrder.setRepairUser(SecurityContextUtil.getCurrentUserName());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("step", EquipmentRepairCode.PROCESSING.getValue());
    return "em/equipmentRepair/repairOrder_repair";
  }

  @RequestMapping(value = "saveRecordOrder")
  @ResponseBody
  public DWZResult recordOrder(Model model, String pattern, String navTabId, String id, RepairOrder order,
      HttpServletRequest request) {
    if (order == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    if (StringUtils.isBlank(order.getRepairMemo()) || StringUtils.isBlank(order.getRepairResult())) {
      return ajaxError(getImeViewMessageI18n(null,
          "lackParameter.M"));
    }
    if (!StringUtils.isBlank(order.getCheckMemo()) || !StringUtils.isBlank(order.getCheckResult())) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String siteCode = getSiteCode();
    String orderCode = order.getOrderCode();
    List<RepairOrderCause> causes = order.getCauses();
    for (RepairOrderCause cause : causes) {
      setCreateInfo(cause);
      cause.setOrderCode(orderCode);
      cause.setSiteCode(siteCode);
    }
    List<RepairOrderPart> parts = order.getParts();
    for (RepairOrderPart part : parts) {
      setCreateInfo(part);
      part.setOrderCode(orderCode);
      part.setSiteCode(siteCode);
    }
    order.setSiteCode(siteCode);
    BatchJobReport report = repairService.doRecordRepairOrder(order, causes, parts);
    if (report.isSuccess()) {
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          navTabId, null, null, null);
    } else {
      return ajaxError(getImeViewMessageI18n(null,
          report.getCause()));
    }
  }

  @RequestMapping("checkOrder")
  public String checkOrder(String navTabId, Model model, String bussinessKey) {
    RepairOrder repairOrder = repairService.getOrderByBusinessKey(bussinessKey, getSiteCode());
    String id = repairOrder.getOrderCode();
    List<RepairOrderCause> causes = repairService.getRepairOrderCause(id, getSiteCode());
    List<RepairOrderPart> parts = repairService.getRepairOrderPart(id, getSiteCode());
    repairOrder.setCauses(causes);
    repairOrder.setParts(parts);
    repairOrder.setCheckUser(SecurityContextUtil.getCurrentUserName());
    List<ECode> eCode = eCodeService.selectECodeList(ECodeEnums.EQUIPMENTREPAIRSTATUS.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("ECode", eCode);
    model.addAttribute("step", EquipmentRepairCode.PROCESSED.getValue());
    model.addAttribute("repairOrder", repairOrder);
    model.addAttribute(NAVTABID, navTabId);
    return "em/equipmentRepair/repairOrder_check";
  }

  @RequestMapping(value = "saveCheckOrder")
  @ResponseBody
  public DWZResult saveCheckOrder(Model model, String pattern, String navTabId, String id, RepairOrder order,
      HttpServletRequest request) {
    if (order == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    if (StringUtils.isBlank(order.getCheckMemo()) || StringUtils.isBlank(order.getCheckResult())) {
      return ajaxError(getImeViewMessageI18n(null,
          "lackParameter.M"));
    }
    order.setSiteCode(getSiteCode());
    repairService.doCheckRepairOrder(order);
    return dialogAjaxDone(
        getImeViewMessageI18n(null, "successfulOperation.M"),
        navTabId, null, null, null);
  }

  @RequestMapping(value = "updateRequestDateTime")
  @ResponseBody
  public DWZResult updateRequestDateTime(Model model, String orderCode, String navTabId, String id) {
    //更新报修时间
    RepairOrder order = repairService.getRepairOrder(orderCode, getSiteCode());
    order.setRequestDateTime(new Date());
    repairService.modifyRepairOrder(order);
    return ajaxDone(null);
  }

}
